package com.webside.points.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.webside.points.model.AnswerEntity;
import com.webside.points.model.ExpertEntity;
import com.webside.points.model.IssueEntity;
import com.webside.points.model.LikeEntity;
import com.webside.points.model.UserEntity;
import com.webside.points.service.AnswerService;
import com.webside.points.service.ExpertService;
import com.webside.points.service.IssueService;
import com.webside.points.service.IssueTypeService;
import com.webside.points.service.LikeService;
import com.webside.points.service.UserService;
import com.webside.points.wechat.Constant;
import com.webside.points.wechat.DateUtil;
import com.webside.points.wechat.PageUtil;
import com.webside.points.wechat.WeChatConfig;
import com.webside.points.wechat.Wechat;

@Controller
@Scope("prototype")
@RequestMapping("/expert/")
public class ExpertContronller {
	
	@Autowired
	ExpertService expertService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	IssueTypeService issueTypeService;
	
	@Autowired
	AnswerService answerService;
	
	@Autowired
	LikeService likeService;
	
	@Autowired
	IssueService issueService;
	
	@RequestMapping("findAllUI")
	public String findAllUI(Model model){
		
		PageUtil pageUtil=new PageUtil();
		  //总记录数
		  int totalCount=expertService.findCount();
		  pageUtil.setTotalCount(totalCount);
		  pageUtil.setCurPage(1);
		  model.addAttribute("pageUtil", pageUtil);
		  model.addAttribute("ExpertType", issueTypeService.findAll());
		return "serve/expert";
	}

	@RequestMapping("findAll")
	public void findAll(String curPage,ExpertEntity expertEntity ,Model model,HttpServletResponse response) throws Exception{
		 
		System.out.println("进入查询专家：>>>"+expertEntity);
		 PageUtil pageUtil=new PageUtil();
		 
		 if(curPage!=null){
			 int cPage=Integer.valueOf(curPage);
			 pageUtil.setCurPage(cPage);
			 cPage=(cPage-1)*10;
			 expertEntity.setCurPage(Integer.valueOf(cPage));
		 }
		 
		 List<ExpertEntity> list=expertService.findAll(expertEntity);
		 int totalCount=expertService.findCount();
		  pageUtil.setContent(list);
		  pageUtil.setTotalCount(totalCount);
		  model.addAttribute("pageUtil", pageUtil);
		  
		  String json = JSON.toJSONString(pageUtil);
			try {
				response.getWriter().write(json);
				response.flushBuffer();
			} catch (Exception e) {
				System.out.println("Error："+e);
			}
			
	  }
	
	
	@RequestMapping("insert")
	public String insert(ExpertEntity expertEntity,String openId){
		
		System.out.println("专家信息：>>>"+expertEntity);
		expertEntity.setCreateTime(new Date(System.currentTimeMillis()));
		expertEntity.setRewardAmount(0.00);
		expertEntity.setLikeCount(0);
		expertEntity.setDislikeCount(0);
		expertEntity.setAuditStatus("0");
		System.out.println(expertService.insert(expertEntity));
		UserEntity userEntity=new UserEntity();
		userEntity.setOpenId(openId);
		userEntity.setExpertId(expertEntity.getId());
		int result = userService.updateExpertId(userEntity);
		if(result==1){
			List<UserEntity> list = userService.findMangeStatus();
			System.out.println("list:"+list);
			
			for(int i=0;i<list.size();i++){
				UserEntity user = list.get(i);
				
				String touser = user.getOpenId();
				String url = Constant.REALM_URL+ "expert/findById?expertId="+expertEntity.getId();
				
				Map<String, Map<String, String>> data = new HashMap<String,Map<String, String>>();
				
				Map<String, String> first=new HashMap<String, String>();
				first.put("value", "申请专家审核通知");
				first.put("color", WeChatConfig.MESSAGE_COLOR);
				
				Map<String, String> keyword1=new HashMap<String, String>();
				keyword1.put("value", expertEntity.getName());
				keyword1.put("color", WeChatConfig.MESSAGE_COLOR);

				Map<String, String> keyword2=new HashMap<String, String>();
				keyword2.put("value", expertEntity.getDescribe());
				keyword2.put("color", WeChatConfig.MESSAGE_COLOR);
				
				Map<String, String> remark=new HashMap<String, String>();
				remark.put("value", "点击进入，进行审核");
				remark.put("color", WeChatConfig.MESSAGE_COLOR);
				
				data.put("first",first);
				data.put("keyword1",keyword1);
				data.put("keyword2",keyword2);
				data.put("remark",remark);
				Wechat.sendMessage(data,WeChatConfig.VEIRFICAATION_request_NOTICE,touser,url);
			}
		}
		
		return "redirect:../user/findByOpenId?openId="+openId;
	}
	
	@RequestMapping("delete")
	public String delete(int id){
		
		System.out.println(expertService.delete(id));
		return "redirect:findAllUI";
	}
	
	@RequestMapping("updateStatus")
	public String updateStatus(int auditStatus,int expertId,String type,String message){
		ExpertEntity expertEntity = expertService.findById(expertId);
		Map<String,Integer> map=new HashMap<String,Integer>();
		map.put("auditStatus", auditStatus);
		map.put("id", expertId);
		int result = expertService.updateStatus(map);
		if(expertEntity.getAuditStatus().equals("0")&&auditStatus==1&&result==1){
			System.out.println("审核通过通知：>>>"+result  +"   "+expertEntity);
			UserEntity userEntity =userService.findExpertId(expertId);
			
			String touser = userEntity.getOpenId();
			
			String url = Constant.REALM_URL+ "user/findByOpenId?openId="+touser;
			
			Map<String, Map<String, String>> data = new HashMap<String,Map<String, String>>();
			
			Map<String, String> first=new HashMap<String, String>();
			first.put("value", "专家审核结果通知。");
			first.put("color", WeChatConfig.MESSAGE_COLOR);
			
			Map<String, String> keyword1=new HashMap<String, String>();
			keyword1.put("value", "已通过");
			keyword1.put("color", WeChatConfig.MESSAGE_COLOR);

			Map<String, String> keyword2=new HashMap<String, String>();
			keyword2.put("value", DateUtil.dateFormat(new Date()));
			keyword2.put("color", WeChatConfig.MESSAGE_COLOR);
			
			Map<String, String> remark=new HashMap<String, String>();
			remark.put("value", "恭喜您成为“中穆问答”的一名专家，进入系统抢答吧！");
			remark.put("color", WeChatConfig.MESSAGE_COLOR);
			
			data.put("first",first);
			data.put("keyword1",keyword1);
			data.put("keyword2",keyword2);
			data.put("remark",remark);
			
			Wechat.sendMessage(data,WeChatConfig.AUDIT_RESULT_NOTICE,touser,url);
			
		}else if(expertEntity.getAuditStatus().equals("0")&&auditStatus==3&&result==1){
			System.out.println("审核通过通知：>>>"+result  +"   "+expertEntity);
			UserEntity userEntity =userService.findExpertId(expertId);
			/*userEntity.setExpertId(0);
			userService.updateExpertId(userEntity);
			expertService.delete(expertId);*/
			
			String touser = userEntity.getOpenId();
			
			String url = Constant.REALM_URL+ "user/findByOpenId?openId="+touser;
			
			Map<String, Map<String, String>> data = new HashMap<String,Map<String, String>>();
			
			Map<String, String> first=new HashMap<String, String>();
			first.put("value", "专家审核结果通知。");
			first.put("color", WeChatConfig.MESSAGE_COLOR);
			
			Map<String, String> keyword1=new HashMap<String, String>();
			keyword1.put("value", "未通过");
			keyword1.put("color", WeChatConfig.MESSAGE_COLOR);

			Map<String, String> keyword2=new HashMap<String, String>();
			keyword2.put("value", DateUtil.dateFormat(new Date()));
			keyword2.put("color", WeChatConfig.MESSAGE_COLOR);
			
			Map<String, String> remark=new HashMap<String, String>();
			try {
				remark.put("value", URLDecoder.decode(message , "UTF-8")+"进入修改资料重新申请。");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			remark.put("color", WeChatConfig.MESSAGE_COLOR);
			
			data.put("first",first);
			data.put("keyword1",keyword1);
			data.put("keyword2",keyword2);
			data.put("remark",remark);
			
			Wechat.sendMessage(data,WeChatConfig.AUDIT_RESULT_NOTICE,touser,url);
		}
		if(type!=null&&type.equals("wechat")){
			return "service/audit-expert";
		}
		return "redirect:findAllUI";
	}
	
	@RequestMapping("deleteBatch")
	public String deleteBatch(){
		
		List<Integer> ids=new ArrayList<Integer>();
		ids.add(1);
		ids.add(2);
		
		System.out.println(expertService.deleteBatch(ids));
		return "redirect:findAllUI";
	}
	
	@RequestMapping("updatePraise")
	@ResponseBody
	public void updatePraise(int expertId,int answerId,String type,int userId){
		ExpertEntity expertEntity = expertService.findById(expertId);
		AnswerEntity answerEntity = answerService.findById(answerId);
		
		
		ExpertEntity expert=new ExpertEntity();
		expert.setId(expertEntity.getId());
		
		
		AnswerEntity answer = new AnswerEntity();
		answer.setId(answerId);
		
		LikeEntity likeEntity=new LikeEntity();
		likeEntity.setAnswerId(answerId);
		likeEntity.setUserId(userId);
		likeEntity.setCreateTime(new Date(System.currentTimeMillis()));
		likeEntity.setStatus("1");
		if(type.equals("like")){
			expert.setLikeCount(expertEntity.getLikeCount()+1);
			expert.setDislikeCount(expertEntity.getDislikeCount());
			answer.setLikeMark(answerEntity.getLikeMark()+1);
			answer.setDislikeMark(answerEntity.getDislikeMark());
			likeEntity.setLike("am-icon-thumbs-up");
			likeEntity.setDisLike("am-icon-thumbs-o-down");
			System.out.println(likeService.insert(likeEntity));
		}else{
			expert.setDislikeCount(expertEntity.getDislikeCount()+1);
			expert.setLikeCount(expertEntity.getLikeCount());
			answer.setDislikeMark(answerEntity.getDislikeMark()+1);
			answer.setLikeMark(answerEntity.getLikeMark());
			likeEntity.setDisLike("am-icon-thumbs-down");
			likeEntity.setLike("am-icon-thumbs-o-up");
			System.out.println(likeService.insert(likeEntity));
		}
		
		System.out.println("entity:>>>"+expert);
		
		expertService.updatePraise(expert);
		answerService.updateLikeMark(answer);
	}
	
	@RequestMapping("removePraise")
	@ResponseBody
	public void removePraise(int expertId,int answerId,String type,int userId){
		ExpertEntity expertEntity = expertService.findById(expertId);
		AnswerEntity answerEntity = answerService.findById(answerId);
		
		
		ExpertEntity expert=new ExpertEntity();
		expert.setId(expertEntity.getId());
		
		AnswerEntity answer = new AnswerEntity();
		answer.setId(answerId);
		
		LikeEntity likeEntity=new LikeEntity();
		likeEntity.setAnswerId(answerId);
		likeEntity.setUserId(userId);

		if(type.equals("like")){
			expert.setLikeCount(expertEntity.getLikeCount()-1);
			expert.setDislikeCount(expertEntity.getDislikeCount());
			answer.setLikeMark(answerEntity.getLikeMark()-1);
			answer.setDislikeMark(answerEntity.getDislikeMark());
			
			System.out.println(likeService.delete(likeEntity));
		}else{
			expert.setDislikeCount(expertEntity.getDislikeCount()-1);
			expert.setLikeCount(expertEntity.getLikeCount());
			answer.setDislikeMark(answerEntity.getDislikeMark()-1);
			answer.setLikeMark(answerEntity.getLikeMark());
			
			System.out.println(likeService.delete(likeEntity));
		}
		
		System.out.println("entity:>>>"+expert+"answer:>>>"+answer);
		
		expertService.updatePraise(expert);
		answerService.updateLikeMark(answer);
	}
	
	@RequestMapping("findExpertInfo")
	public String findExpertInfo(int expertId,Model model,HttpServletRequest request){
		
		System.out.println("进入专家信息查询："+expertId);
		
		if(expertId!=0){
			ExpertEntity expertEntity = expertService.findById(expertId);
			model.addAttribute("expertEntity", expertEntity);
			
			Map<String,Integer> expert=new HashMap<String,Integer>();
			expert.put("expertId", expertEntity.getId());
			List<IssueEntity> expertList=issueService.findRecord(expert);
			model.addAttribute("answerCount", expertList.size());
			
			Map<String,Integer> map=new HashMap<String,Integer>();
			map.put("expertId", expertEntity.getId());
			List<IssueEntity> issueList=issueService.findRecord(map);
			model.addAttribute("issueList", issueList);
			
			String openId = (String) request.getSession().getAttribute("openId"); 
			UserEntity UserEntity = userService.findByOpenId(openId);
			model.addAttribute("user", UserEntity);
		}
		
		return "service/expert-info";
	}
	
	@RequestMapping("findExpertAnswer")
	public void findExpertAnswer(int page,int size,int expertId,HttpServletResponse response){
		
		System.out.println("进入专家信息查询："+expertId);
		
		if(expertId!=0){
			Map<String,Integer> map=new HashMap<String,Integer>();
			map.put("expertId", expertId);
			if(page!=0){
				 int cPage=page;
				 cPage=(cPage-1)*10;
				 map.put("page", cPage);
				 map.put("size", size);
			 }
			
			List<IssueEntity> expertList=issueService.findRecord(map);
			
			String json = JSON.toJSONString(expertList);
			try {
				response.getWriter().write(json);
				response.flushBuffer();
			} catch (Exception e) {
				System.out.println("JsonError："+e);
			}
			
		}
		
	}
	@RequestMapping("findAuditExpert")
	public void findAuditExpert(int page,int size,HttpServletResponse response){
		System.out.println("审核专家："+page+"  "+size);
		Map<String,Integer> map=new HashMap<String,Integer>();
		if(page!=0){
			 int cPage=page;
			 cPage=(cPage-1)*10;
			 map.put("page", cPage);
			 map.put("size", size);
		 }
		List<ExpertEntity> expertList = expertService.findAuditExpert(map);
		String json = JSON.toJSONString(expertList);
		try {
			response.getWriter().write(json);
			response.flushBuffer();
		} catch (Exception e) {
			System.out.println("JsonError："+e);
		}
	}
	@RequestMapping("findById")
	public String findById(int expertId,Model model){
		System.out.println("进入专家信息查询：expertId"+expertId);
		
		ExpertEntity expertEntity = expertService.findById(expertId);
		
		model.addAttribute("expertEntity", expertEntity);
		if(!expertEntity.getAuditStatus().equals("0")){
			return "service/expert-success";
		}
		
		return "service/expert-content";
	}
	
	@RequestMapping("findByExpertInfo")
	public String findByExpertInfo(int expertId,Model model){
		System.out.println("进入专家信息查询：expertId"+expertId);
		
		ExpertEntity expertEntity = expertService.findById(expertId);
		model.addAttribute("issueTypeList", issueTypeService.findAll());
		model.addAttribute("expertEntity", expertEntity);
		
		return "service/expert";
	}
	@RequestMapping("update")
	public String update(ExpertEntity expertEntity,HttpServletRequest request){
		expertEntity.setAuditStatus("0");
		System.out.println("进入专家修改："+expertEntity);
		int result = expertService.update(expertEntity);
		if(result==1){
			List<UserEntity> list = userService.findMangeStatus();
			System.out.println("list:"+list);
			
			for(int i=0;i<list.size();i++){
				UserEntity user = list.get(i);
				
				String touser = user.getOpenId();
				String url = Constant.REALM_URL+ "expert/findById?expertId="+expertEntity.getId();
				
				Map<String, Map<String, String>> data = new HashMap<String,Map<String, String>>();
				
				Map<String, String> first=new HashMap<String, String>();
				first.put("value", "申请专家审核通知");
				first.put("color", WeChatConfig.MESSAGE_COLOR);
				
				Map<String, String> keyword1=new HashMap<String, String>();
				keyword1.put("value", expertEntity.getName());
				keyword1.put("color", WeChatConfig.MESSAGE_COLOR);

				Map<String, String> keyword2=new HashMap<String, String>();
				keyword2.put("value", expertEntity.getDescribe());
				keyword2.put("color", WeChatConfig.MESSAGE_COLOR);
				
				Map<String, String> remark=new HashMap<String, String>();
				remark.put("value", "点击进入，进行审核");
				remark.put("color", WeChatConfig.MESSAGE_COLOR);
				
				data.put("first",first);
				data.put("keyword1",keyword1);
				data.put("keyword2",keyword2);
				data.put("remark",remark);
				Wechat.sendMessage(data,WeChatConfig.VEIRFICAATION_request_NOTICE,touser,url);
			}
		}
		String openId = (String) request.getSession().getAttribute("openId");
		return "redirect:../user/findByOpenId?openId="+openId;
	}
	
	@RequestMapping("findInfo")
	public String findInfo(int expertId,Model model){
		System.out.println("进入专家信息查询：expertId"+expertId);
		
		ExpertEntity expertEntity = expertService.findById(expertId);
		
		model.addAttribute("expert", expertEntity);
		
		return "serve/expertInfo";
	}
}
